﻿using SGA.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SGA.Authentication.User
{
    public partial class EditRegister : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                using (var bd = new MailingEntities())
                {
                    SystemUsers user = (from member in bd.SystemUsers
                                        where member.Username == User.Identity.Name
                                        select member).SingleOrDefault();
                    if (user != null)
                    {
                        MembershipUser u = Membership.GetUser(user.Username);
                        NameTextBox.Text = user.Name;
                        UsernameTextBox.Text = user.Username;
                        AliasTextBox.Text = user.Alias;
                        PasswordTextBox.Attributes.Add("value", u.GetPassword());
                        DropDownListRole.SelectedValue = user.AccessRoles.Role;
                        EnableCheckBox.Checked = (bool)user.Enable;
                        IdUserTextBox.Value = user.Id.ToString();
                    }
                }
            }
        }

        /// <summary>
        /// Method to verify if the updating data its valid
        /// this is to ensure funcional requirements nr 3
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void UpdateButton_Click(object sender, EventArgs e)
        {
            try
            {
                int id = Convert.ToInt32(IdUserTextBox.Value);
                using (var bd = new MailingEntities())
                {
                    SystemUsers user = (from member in bd.SystemUsers
                                        where member.Id == id
                                        select member).SingleOrDefault();
                    if (user.Alias != AliasTextBox.Text)
                    {
                        var query = from member in bd.SystemUsers
                                    where member.Alias == AliasTextBox.Text
                                    select member;
                        if (query.Count() > 0)
                        {
                            throw new Exception("Alias já existe. Não pode haver duplicações.");
                        }
                    }
                    AccessRoles queryRole = (from role in bd.AccessRoles
                                             where role.Role == DropDownListRole.SelectedValue
                                             select role).SingleOrDefault();

                    user.Name = NameTextBox.Text;
                    user.Alias = AliasTextBox.Text;
                    user.Enable = EnableCheckBox.Checked;
                    user.AccessRolesId = queryRole.Id;

                    MembershipUser memberShip = Membership.GetUser(user.Username);
                    if (memberShip.GetPassword() != PasswordTextBox.Text)
                    {
                        memberShip.ChangePassword(memberShip.ResetPassword(), PasswordTextBox.Text);
                    }

                    memberShip.IsApproved = EnableCheckBox.Checked;

                    if (!Roles.IsUserInRole(memberShip.UserName, DropDownListRole.SelectedValue))
                    {
                        DeleteUserRoles(memberShip.UserName);
                        Roles.AddUserToRole(memberShip.UserName, DropDownListRole.SelectedValue);
                    }

                    bd.SaveChanges();
                    Membership.UpdateUser(memberShip);
                    
                    NotificationLabel.Text = String.Format("{0} foi atualizado com sucesso", memberShip.UserName);
                    NotificationLabel.CssClass = "mySuccess";
                }
            }
            catch (Exception ex)
            {
                NotificationLabel.Text = String.Format("{0}", ex.Message);
                NotificationLabel.CssClass = "Alert";
            }
        }

        /// <summary>
        /// Method to delete user from role
        /// </summary>
        /// <param name="username"></param>
        private void DeleteUserRoles(string username)
        {
            foreach (var role in Roles.GetRolesForUser(username))
                Roles.RemoveUserFromRole(username, role);
        }
    }
}